package com.btpn.custody.web.m006.action;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;

import com.btpn.custody.bean.DailyEQ;
import com.btpn.custody.common.Constant;
import com.btpn.custody.dao.IUser;
import com.btpn.custody.entity.User;
import com.opensymphony.xwork2.ActionSupport;

@ParentPackage(value = "custody")
@Results({
		@Result(name="input", location="t_exportEQ_manual")
})
public class ExportEquationAction extends ActionSupport implements ServletRequestAware {

	/*=============================================== C O N S T A N T =========================================*/
	private static final long serialVersionUID = 6269268717899456543L;
	
	/*=============================================== M E M B E R =============================================*/		
	private HttpServletRequest servletRequest;
	
	@Autowired
	private DailyEQ dailyEQ;
	
	@Autowired
	private IUser userDaoHibernate;
	
	/*=============================================== B E H A V I O R =========================================*/
	@Action(value = "/exportEQ-manual", results = { @Result(name="success", location="t_exportEQ_manual") })
	public String exportEQ() {
		
		return SUCCESS;
	}
	
	/*
	 * PURPOSE : export to EQ
	 * USER : admin
	 */
	@Action(value = "/exportedEQ", results = { 
			@Result(name="success", location="t_exportEQ_manual" )
	})
	public String exportedEQ() {
		
		// validasi jam 3pagi - 6sore
		Integer nowHour = Integer.parseInt(new SimpleDateFormat("HH").format(new Date()));
		if ((nowHour>3) & (nowHour<18)) {
			User user = userDaoHibernate.get(SecurityContextHolder.getContext().getAuthentication().getName());
			
			String result = dailyEQ.sendDailyToEQ(user.getUsername());
			if (result.equals(Constant.STATUS__SUCCESS)) {
				addActionMessage("Success");
			} else {
				addActionError("Error : " + Constant.NEW_LINE + result);
			}
			
			addActionMessage("Success export to EQ");
		} else {
			addActionError("Export only can be done at 3am - 6pm");
		}
		return SUCCESS;
	}
	
	/*=============================================== G E T T E R   &   S E T T E R ===========================*/
	public HttpServletRequest getServletRequest() {
		return servletRequest;
	}
	
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.servletRequest = request;
	}
}
